package com.nantai.jiafang.nantaijiafang.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.MyApplication;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.activity.adapter.Login_select_adapter;
import com.nantai.jiafang.nantaijiafang.bean.FabricBatchInfo;
import com.nantai.jiafang.nantaijiafang.bean.ProductionOrderInfo;
import com.nantai.jiafang.nantaijiafang.deviceManager.bean.User;
import com.nantai.jiafang.nantaijiafang.deviceManager.Constans;
import com.nantai.jiafang.nantaijiafang.deviceManager.devicemanager.OperateActivity;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.Error;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.HttpClient;
import com.nantai.jiafang.nantaijiafang.deviceManager.http.ResponseHandler;
import com.nantai.jiafang.nantaijiafang.deviceManager.preference.PreferencesUtil;
import com.nantai.jiafang.nantaijiafang.deviceManager.utils.MessagePop;
import com.nantai.jiafang.nantaijiafang.fragment.Bundle_SerInfo;
import com.nantai.jiafang.nantaijiafang.zhijian.fragment.ZhijianFragment_select;
import com.nantai.jiafang.nantaijiafang.nt5s.Activity.NT5SActivity;
import com.nantai.jiafang.nantaijiafang.nt5s.utils.Tools;
import com.nantai.jiafang.nantaijiafang.view.Public;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import info.hoang8f.android.segmented.SegmentedGroup;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/9/25.
 */

public class Login_Select extends AppCompatActivity {
    private int login_type=0;

    private SegmentedGroup loginType;
    private ListView listView;
    private ArrayList<String> list=new ArrayList<>();
    ProgressDialog progressDialog;
    public static String userId = "";
    private DbManager db;
    private ArrayList<Bundle_SerInfo> accounts;
    private boolean rememberaccount;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_select);
        final Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle(Public.NAME+"-"+getString(R.string.select_title));
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
            actionBar.setHomeButtonEnabled(true);
        }
        progressDialog=new ProgressDialog(Login_Select.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在登陆，请稍候");
        listView=(ListView)findViewById(R.id.login_listview);
        listView.setOnItemClickListener((parent,view,position,id)->{
            Bundle_SerInfo account=accounts.get(position);
            if (account.getSystemName().contains("面料")) {
                progressDialog.show();
                login_mianliao(account.getSystemLoginName(), account.getSystemPassword());
            }else if (account.getSystemName().contains("设备")) {
                progressDialog.show();
                login_device(account.getSystemLoginName(), account.getSystemPassword());
            }else if (account.getSystemName().contains("5S")){
                progressDialog.show();
                if (Tools.isNetAvailuable(Login_Select.this)) {
                    login_5S(account.getSystemLoginName(), account.getSystemPassword());
                } else {
                    Tools.showToast(Login_Select.this, "当前网络不可用，请检查网络");
                }
            }else if (account.getSystemName().contains("质检")) {
                login_zhjian(account.getSystemLoginName(), account.getSystemPassword());
            }

        });
        db = x.getDb(MyApplication.daoConfig);
       /* loginType = (SegmentedGroup)rootview.findViewById(R.id.segmented2);
       // loginType.check(R.id.ml_btn);
        loginType.setTintColor(0xFF1b7ce8);
        loginType.setOnCheckedChangeListener(this);*/
        initUI();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initUI(){
        Bundle bunde=getIntent().getExtras();
        accounts=bunde.getParcelableArrayList("account");
        rememberaccount=bunde.getBoolean("remember");
        list.clear();
        for (Bundle_SerInfo bundle_serInfo :
                accounts) {
            list.add(bundle_serInfo.getSystemName().split(":")[1]);
        }
        Login_select_adapter arrayAdapter=new Login_select_adapter(this,R.layout.login_select_item,list);
        listView.setAdapter(arrayAdapter);

    }
    private void login_mianliao(String account,String password){
        //面料管理登录
        RequestParams params = new RequestParams(Constans.MIANLIAO + "login");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("loginName", account);
        params.addBodyParameter("password", password);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("返回结果：" + result);
                String results[] = result.split(":");
                if (results[0].equals("1")) {
                    progressDialog.dismiss();
                    SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString(IConstant.SP_USERNAME, results[1]);
                    Data.username=results[1];
                    editor.commit();
                    User user = new  User();
                    PreferencesUtil.setIsSave(Login_Select.this, rememberaccount);
                    user.setUserName(account);
                    user.setPassWord(password);
                    user.setCompany(Public.NAME);
                    PreferencesUtil.saveUser(Login_Select.this, user);
                    userId ="admin"; //et_username.getText().toString();
                    startActivity(new Intent(Login_Select.this, MainActivity.class));
                   // progressDialog.setMessage("正在更新数据");
                   // progressDialog.show();
                    //updateDataFromNet();

                } else {
                    progressDialog.dismiss();
                    Tools.showToast(Login_Select.this, results[1]);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                Tools.showToast(Login_Select.this, "请求出错，请重试");
                //System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(Login_Select.this, "cancelled", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });
    }
    private void login_device(String account,String password){
        Map<String, String> params = new HashMap<>();
        //String inputpassword = et_pwd.getText().toString();
        params.put("user_name", account);
        params.put("password", password);
        HttpClient client = new HttpClient(this);
        Call call = client.service().login(params);

        Log.e("2222", "login_device: "+call.request().url().toString());
        client.request(call, new ResponseHandler() {
            @Override
            public void onSuccess(Object o) {
                User user=(User)o;
                PreferencesUtil.setIsSave(Login_Select.this, rememberaccount);
                user.setUserName(account);
                user.setPassWord(password);
                user.setCompany(Public.NAME);
                PreferencesUtil.saveUser(Login_Select.this, user);
                //设备管理登录
                startActivity(new Intent(Login_Select.this, OperateActivity.class));
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(int code, Error e) {
                Log.e("66666", "onFailure: "+e.getMessage() );
                if(e.getCode().equals("CODE_USER_ERROR"))
                {
                    progressDialog.dismiss();
                    MessagePop.ToastMessage(Login_Select.this,e.getMessage());
                }else
                {
                    progressDialog.dismiss();
                    MessagePop.ToastMessage(Login_Select.this, "网络异常");
                }
            }
        });
    }

    private void login_5S(String account,String password){
      //startActivity(new Intent(Login_Select.this,  NT5SActivity.class));
      //  progressDialog.dismiss();
           RequestParams params = new RequestParams(com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URL+ "login");
            //params.setSslSocketFactory(...); // 设置ssl
            params.addBodyParameter("loginName",account);
            params.addBodyParameter("Password", password);

//            System.out.println("请求的URL：" + params.toString());
//          xutils框架（登录检测账户密码）
           x.http().post(params, new Callback.CommonCallback<String>() {

                @Override
                public void onSuccess(String result) {
//           System.out.println("返回结果：" + result);
                    String results[] = result.split(":");
                    if (results[0].equals("1")) {
                       // SjieTools.showToast(mcontext, "登录成功");
//USER配置文件更新
                        Data.NT5S_Account=results[1];
                        SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(IConstant.SP_USERNAME, results[1]);
                        editor.commit();
//记住密码配置
                        if (rememberaccount) {
                            Tools.setSharedValue(Login_Select.this, IConstant.FILE_USER, IConstant.SP_LOGIN_NAME, account);
                            Tools.setSharedValue(Login_Select.this, IConstant.FILE_USER, IConstant.SP_LOGIN_PWD, password);
                            Tools.setSharedValue(Login_Select.this, IConstant.FILE_USER, IConstant.SP_ISPWD_REMEMBER, "1");
                        } else {
                            Tools.setSharedValue(Login_Select.this, IConstant.FILE_USER, IConstant.SP_LOGIN_NAME, "");
                            Tools.setSharedValue(Login_Select.this, IConstant.FILE_USER, IConstant.SP_LOGIN_PWD, "");
                            Tools.setSharedValue(Login_Select.this, IConstant.FILE_USER, IConstant.SP_ISPWD_REMEMBER, "0");
                        }
                        userId = account;
                        progressDialog.setMessage("正在更新数据");
                        progressDialog.show();
//PublicPreferences配置文件写入user=User的json数据  new Gson().toJson(user
                        User user= new User();
                        user.setUserName(account);
                        user.setPassWord(password);
                        user.setName(results[1]);
                        PreferencesUtil.saveUser(Login_Select.this.getApplicationContext(), user);
                        startActivity(new Intent(Login_Select.this, NT5SActivity.class));
                    } else {
                        progressDialog.dismiss();
                       // SjieTools.showToast(mcontext, results[1]);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    progressDialog.dismiss();
                    Tools.showToast(Login_Select.this, "请求出错，请重试");
//                    System.out.println("出错：" + ex.getCause().toString());
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    progressDialog.dismiss();
                  //  Toast.makeText(mcontext, "cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFinished() {
                    progressDialog.dismiss();
                }
            });
    }
    private void login_zhjian(String account,String password){
        //startActivity(new Intent(Login_Select.this,  NT5SActivity.class));
        //  progressDialog.dismiss();
        RequestParams params = new RequestParams(IConstant.NT_ZHIJIAN+ "AppHandler.ashx?opType=login");
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("loginName",account);
        params.addBodyParameter("Password", password);

//            System.out.println("请求的URL：" + params.toString());
//          xutils框架（登录检测账户密码）
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
//           System.out.println("返回结果：" + result);
                String results[] = result.split(":");
                if (results[0].equals("1")) {
                    // SjieTools.showToast(mcontext, "登录成功");
//USER配置文件更新
                    Data.ZHIJIAN_Account=results[1];
                    SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString(IConstant.SP_USERNAME, results[1]);
                    editor.commit();
                    userId = account;
                    progressDialog.setMessage("正在更新数据");
                    progressDialog.show();
                    getSupportFragmentManager().beginTransaction()
                            .addToBackStack(null)
                            .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                            .add(R.id.select_contain, new ZhijianFragment_select())
                            .commit();
                } else {
                    progressDialog.dismiss();
                    // SjieTools.showToast(mcontext, results[1]);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                Tools.showToast(Login_Select.this, "请求出错，请重试");
//                    System.out.println("出错：" + ex.getCause().toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                //  Toast.makeText(mcontext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });

    }
    //同步数据
    private void updateDataFromNet() {
        RequestParams params = new RequestParams(Constans.GETDATA);
        Log.e("33333", "updateDataFromNet: "+params.getUri());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                Tools.showToast(Login_Select.this, "数据同步成功");
                anaylysisData(result);
                Log.e("1111111111111111","请求的URL：" + String.valueOf(result.length()));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                onFailure();
                startActivity(new Intent(Login_Select.this, MainActivity.class));
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //解析获取到的数据
    private void anaylysisData(String result) {
        Gson gson = new Gson();
        try {
            List<String> list_keys = new ArrayList<>();
            JSONObject jo = new JSONObject(result);
            Iterator it_color = jo.keys();
            while (it_color.hasNext()) {
                String key = it_color.next().toString();
                list_keys.add(key);
            }
            Log.e("444444", "key:"+list_keys.size());
            ArrayList<List<FabricBatchInfo>> mianliao=new ArrayList<>();
            ArrayList<List<ProductionOrderInfo>> shebei=new ArrayList<>();
            for (int i = 0; i < list_keys.size(); i++) {
                if (list_keys.get(i).contains("ML")) {
                    List<FabricBatchInfo> list_fabric = gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<FabricBatchInfo>>() {
                    }.getType());
                    for (int j = 0; j < list_fabric.size(); j++) {
                        list_fabric.get(j).setIsRead("0");
                        list_fabric.get(j).setUserId(userId);
                    }
                    mianliao.add(list_fabric);
                    System.out.println("list1:"+list_fabric.size());
                    insertIntoFabricDB(list_fabric);
                }else if(list_keys.get(i).contains("SCDD")){
                    List<ProductionOrderInfo> list_production = gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<ProductionOrderInfo>>() {
                    }.getType());
                    for (int j = 0; j < list_production.size(); j++) {
                        list_production.get(j).setIsRead("0");
                        list_production.get(j).setUserId(userId);
                    }
                    shebei.add(list_production);
                    System.out.println("list2:"+list_production.size());
                    insertIntoProductionDB(list_production);
                }
            }
            Data.mianliao_data=mianliao;
            Data.shenchan_data=shebei;
            progressDialog.dismiss();
            startActivity(new Intent(Login_Select.this, MainActivity.class));
           // getFragmentManager().popBackStack();
        } catch (JSONException e) {
            System.out.println("GSON出错");
            Toast.makeText(this, "GSON解析出错", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(Login_Select.this, MainActivity.class));
           // getFragmentManager().popBackStack();
        }
    }
    private void onFailure() {
        progressDialog.dismiss();
        Tools.showToast(Login_Select.this, "获取更新数据失败");
//        startActivity(new Intent(mcontext, MainActivity.class));
//        finish();
    }
    private void insertIntoFabricDB(List<FabricBatchInfo> list) {
        try {
            FabricBatchInfo info = list.get(0);
            List<FabricBatchInfo> list_db;
            list_db = db.selector(FabricBatchInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId","=",userId).findAll();
            if (list_db==null||list_db.size()==0){
                System.out.println("插入数量1："+list.size());
                db.save(list);
            }
        } catch (DbException e) {
            Toast.makeText(this, "插入数据库出错1", Toast.LENGTH_SHORT).show();
            System.out.println("插入数据库出错1");
        }
    }

    private void insertIntoProductionDB(List<ProductionOrderInfo> list) {
        try {
            ProductionOrderInfo info = list.get(0);
            List<ProductionOrderInfo> list_db;
            list_db = db.selector(ProductionOrderInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId","=",userId).findAll();
            if (list_db==null||list_db.size()==0){

                System.out.println("插入数量2："+list.size());
                db.save(list);

            }
        } catch (DbException e) {
            Toast.makeText(this, "插入数据库出错2", Toast.LENGTH_SHORT).show();
            System.out.println("插入数据库出错2");
        }
    }
    //登录入口选择
    /*@Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        
            switch (checkedId) {
                case R.id.ml_btn: {
                    login_type=0;
                }
                break;
                case R.id.device_btn: {
                    login_type=1;
                }
                default:
                    // Nothing to do
            }
        if (SjieTools.isNetAvailuable(Login_Select.this)) {
            Intent intent=new Intent(getActivity(), com.nantai.jiafang.nantaijiafang.nt5s.Activity.LoginActivity2.class);
            startActivity(intent);
           // select();
        } else {
            SjieTools.showToast(Login_Select.this, "当前网络不可用，请检查网络");
        }
  
    }*/
//    private void select() {
//        if(Public.NAME.equals("瀚隆"))
//        {
//            Constans.BASE_URL="http://222.188.95.94:8069/hlService/index.php/UserApi/";
//        }
//        else
//        {
//            Constans.BASE_URL="http://58.214.250.250:8010/ntService/index.php/UserApi/";
//        }
//        if(login_type==0)
//        {
//            //面料管理登录
//            RequestParams params = new RequestParams(IConstant.URL_LOGIN + "login");
//            //params.setSslSocketFactory(...); // 设置ssl
//            params.addBodyParameter("loginName", et_username.getText().toString());
//            params.addBodyParameter("password", et_pwd.getText().toString());
//
//            System.out.println("请求的URL：" + params.toString());
//            x.http().post(params, new Callback.CommonCallback<String>() {
//                @Override
//                public void onSuccess(String result) {
//                    System.out.println("返回结果：" + result);
//                    String results[] = result.split(":");
//                    if (results[0].equals("1")) {
//                        SjieTools.showToast(Login_Select.this, "登录成功");
//                        SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
//                        SharedPreferences.Editor editor = sp.edit();
//                        editor.putString(IConstant.SP_USERNAME, results[1]);
//                        editor.commit();
//                        User user = new  User();
//                        PreferencesUtil.setIsSave(LoginActivity2.this, cb_remember_pwd.isChecked());
//                        user.setUserName(et_username.getText().toString());
//                        user.setPassWord(et_pwd.getText().toString());
//                        user.setCompany(company.getSelectedItem().toString());
//                        PreferencesUtil.saveUser(LoginActivity2.this, user);
//
//                        userId = et_username.getText().toString();
//                        progressDialog.setMessage("正在更新数据");
//                        progressDialog.show();
//                        updateDataFromNet();
//                        //startActivity(new Intent(Login_Select.this, MainActivity.class));
//
//                    } else {
//                        progressDialog.dismiss();
//                        SjieTools.showToast(Login_Select.this, results[1]);
//                    }
//                }
//
//                @Override
//                public void onError(Throwable ex, boolean isOnCallback) {
//                    progressDialog.dismiss();
//                    SjieTools.showToast(Login_Select.this, "请求出错，请重试");
//                    //System.out.println("出错：" + ex.getCause().toString());
//
//                }
//
//                @Override
//                public void onCancelled(CancelledException cex) {
//                    progressDialog.dismiss();
//                    Toast.makeText(Login_Select.this, "cancelled", Toast.LENGTH_LONG).show();
//                }
//
//                @Override
//                public void onFinished() {
//                    progressDialog.dismiss();
//                }
//            });
//        }else
//        {
//            Map<String, String> params = new HashMap<>();
//            String inputpassword = et_pwd.getText().toString();
//            params.put("user_name", et_username.getText().toString());
//            params.put("password", inputpassword);
//            HttpClient client = new HttpClient(LoginActivity2.this);
//            Call call = client.service().login(params);
//
//            client.request(call, new ResponseHandler<User>() {
//                @Override
//                public void onSuccess(User user) {
//                    //登陆成功，保存用户信息
//                    PreferencesUtil.setIsSave(LoginActivity2.this, cb_remember_pwd.isChecked());
//                    user.setUserName(et_username.getText().toString());
//                    user.setPassWord(et_pwd.getText().toString());
//                    user.setCompany(company.getSelectedItem().toString());
//                    PreferencesUtil.saveUser(LoginActivity2.this, user);
//                    //设备管理登录
//                    startActivity(new Intent(LoginActivity2.this, OperateActivity.class));
//                    progressDialog.dismiss();
//                }
//
//                @Override
//                public void onFailure(int code, Error e) {
//                    if(e.getCode().equals("CODE_USER_ERROR"))
//                    {
//                        progressDialog.dismiss();
//                        MessagePop.ToastMessage(LoginActivity2.this,e.getMessage());
//                    }else
//                    {
//                        progressDialog.dismiss();
//                        MessagePop.ToastMessage(LoginActivity2.this, "网络异常");
//                    }
//
//                }
//            });
//
//
//        }
//    }
}
